﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Swift;
using SCM;

public class UnitsUI : UIBase {

    public GameObject UUI;
    public MapGround MG;

    Button curBtn = null;
    public string CurUnitType { get; set; }
    public void OnSelUnit(string c)
    {
        curBtn = btns[c];
        CurUnitType = c;
        RefreshBtns();
    }

    public bool CheckColdown(string type)
    {
        return coldown.ContainsKey(type) && coldown[type] >= 1;
    }

    public void ResetColdown(string type)
    {
        coldown[type] = 0;
    }

    Dictionary<string, int> builder = new Dictionary<string, int>();
    Dictionary<string, float> coldown = new Dictionary<string, float>();
    Dictionary<string, Button> btns = new Dictionary<string, Button>();
    protected override void StartOnlyOneTime()
    {
        Room4Client.OnBattleBegin += Room4Client_OnBattleBegin;
        Room4Client.OnBattleEnd += Room4Client_OnBattleEnd;
        Room4Client.NotifyUnitRemoved += Room4Client_NotifyUnitRemoved;
        Room4Client.OnConstructingCompleted += Room4Client_OnConstructingCompleted;

        var cs = UnitConfiguration.AllConfigNames;
        var num = 0;
        for (var i = 0; i < cs.Length; i++)
        {
            var c = cs[i];
            var cfg = UnitConfiguration.GetDefaultConfig(c);
            if (cfg.MaxVelocity > 0 && !cfg.OutOfControl && !cfg.NeutralType)
            {
                var uui = Instantiate(UUI) as GameObject;
                uui.SetActive(true);
                uui.transform.SetParent(UUI.transform.parent);
                uui.transform.Find("Name").GetComponent<Text>().text = cfg.DisplayName;
                uui.transform.Find("Cost").GetComponent<Text>().text = cfg.Cost.ToString();
                var btn = uui.GetComponent<Button>();
                btn.onClick.AddListener(
                    new UnityEngine.Events.UnityAction(
                        () => OnSelUnit(c)));

                uui.transform.localScale = Vector3.one;
                uui.transform.localPosition = Vector3.zero;
                num++;

                btns[c] = btn;
                btn.gameObject.SetActive(false);
            }
        }

        gameObject.SetActive(false);
    }

    private void Room4Client_OnConstructingCompleted(Unit u)
    {
        if (!gameObject.activeSelf)
            return;

        RefreshBtns();

        if (u.Player == GameCore.Instance.MePlayer && u.cfg.GenUnitTypes != null)
            foreach (var gu in u.cfg.GenUnitTypes)
                builder[gu] = (builder.ContainsKey(gu) ? builder[gu] : 0) + 1;
    }

    private void Room4Client_NotifyUnitRemoved(Unit u)
    {
        if (!gameObject.activeSelf)
            return;

        RefreshBtns();

        if (u.Player == GameCore.Instance.MePlayer && u.cfg.GenUnitTypes != null)
        {
            foreach (var gu in u.cfg.GenUnitTypes)
            {
                if (builder.ContainsKey(gu))
                    builder[gu] = builder[gu] - 1;
            }
        }
    }

    private void Room4Client_OnBattleEnd(Room arg1, string arg2, bool arg3)
    {
        // builder.Clear();
        // coldown.Clear();
    }

    private void Room4Client_OnBattleBegin(Room4Client r, bool isReplay)
    {
        CurUnitType = null;
        gameObject.SetActive(true);
        foreach (var c in btns.Keys)
            btns[c].gameObject.SetActive(false);

        builder.Clear();
        coldown.Clear();
    }

    private void Update()
    {
        RefreshColdown(Time.deltaTime);
    }

    void RefreshColdown(float dt)
    {
        foreach (var c in btns.Keys)
        {
            var btn = btns[c];
            if (!btn.gameObject.activeInHierarchy)
                continue;

            var cfg = UnitConfiguration.GetDefaultConfig(c);
            var dd = 2.5f * dt / (float)cfg.ConstructingTime;
            dd *= builder[c];
            if (!coldown.ContainsKey(c))
                coldown[c] = 0;
            else
                coldown[c] += dd;

            var p = coldown[c] > 1 ? 1 : coldown[c];
            btn.transform.Find("OK").GetComponent<Image>().fillAmount = p;
        }
    }

    void RefreshBtns()
    {
        foreach (var c in btns.Keys)
        {
            var cfg = UnitConfiguration.GetDefaultConfig(c);
            var ok = true;
            if (cfg.Prerequisites != null && cfg.Prerequisites.Length > 0)
            {
                ok = false;
                foreach (var p in cfg.Prerequisites)
                {
                    if (MG.Room.GetAllMyUnits((u) =>
                        u.UnitType == p && 
                        u.BuildingCompleted).Length > 0)
                    {
                        ok = true;
                        break;
                    }
                }
            }

            var btn = btns[c];
            btn.gameObject.SetActive(ok);
            btn.transform.Find("Check").gameObject.SetActive(btn == curBtn);
        }
    }
}
